package com.yc154.springmvc1.demos.web;

import com.yc154.springmvc1.demos.biz.UserBiz;
import com.yc154.springmvc1.demos.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserDo {

    public UserDo(){
        System.out.println("========UserDo========");
    }

    @Autowired
    UserBiz userBiz;

    @RequestMapping("reg")
    public Map<?,?> reg(@Valid User user, Errors errors) {
        if (errors.hasErrors()) {
            List<ObjectError> allErrors = errors.getAllErrors();
            return Map.of("code", 0, "msg", "字段验证错误",
                    "data",allErrors);
        }
        userBiz.reg(user);
        return Map.of("code", 1, "msg", "字段验证通过", "data", user);
    }

    // json 不需要日期类型转换, 因为 jackson 帮我们完成了转换
    @RequestMapping("reg1")
    public Map<?,?> reg1(@RequestBody @Valid User user, Errors errors) {
        if (errors.hasErrors()) {
            List<ObjectError> allErrors = errors.getAllErrors();
            return Map.of("code", 0, "msg", "字段验证错误",
                    "data",allErrors);
        }
        return Map.of("code", 1, "msg", "字段验证通过", "data", user);
    }

    @Value("${upload.webPath}")
    String webPath;
    @Value("${upload.diskPath}")
    String diskPath;

    @PostMapping("upload")
    public Map<?,?> upload(@RequestParam("abc") MultipartFile file) throws IOException {
        String dir = diskPath;
        String prefix = file.getOriginalFilename().substring(0,
                file.getOriginalFilename().lastIndexOf("."));
        String suffix = file.getOriginalFilename().substring(prefix.length());
        String newName = UUID.randomUUID().toString() + suffix;
        String diskPath = dir + newName;
        String webPath = this.webPath + newName;
        // 保存文件
        file.transferTo(new File(diskPath));
        return Map.of("code",1,"msg","文件上传成功", "data", webPath);
    }

}
